package Service;

import bean.Customer;

import java.util.Arrays;

/**
 * @author caesar
 * @date 2025/7/8
 * @Description:
 * @apiNote
 */
public class CustomerList {
    private static Customer[] customers = new Customer[3];//先给一个初始长度
    private static int count;//默认值是0，它代表已经放到数组中的客户对象的个数
    public static void addCustomer(Customer customer){
        //数组的正确下标范围[0, 长度-1]
        if (count >= customers.length) {
//            System.out.println("数组已满！");
            //扩容
//            customers = Arrays.copyOf(customers, customers.length + 1);//每次扩1个，优点：一点不浪费，缺点：扩容频率过高
//            customers = Arrays.copyOf(customers, customers.length * 2);//每次扩容2倍，优点：扩容频率低，缺点：有可能浪费
            customers = Arrays.copyOf(customers, (int)(customers.length * 1.5));//每次扩容1.5倍，对
            //高级点的写法
//            customers = Arrays.copyOf(customers, customers.length << 1);//每次扩容2倍
//            customers = Arrays.copyOf(customers, customers.length + (customers.length>>1));//每次扩容1.5倍
        }
        customers[count++] = customer;
    }

    public static Customer[] getAllCustomers(){
//        return customers;//可以，但不完美，因为customers数组中装满的null值
        //优化一下，有count个，返回count个
        return Arrays.copyOf(customers, count);
    }

    public static void replaceCustomer(int index, Customer newCustomer){
        //替换原来index位置的客户对象
        customers[index] = newCustomer;
    }

    public static Customer getCustomer(int id){
        //下标 = id - 1
        int index = id - 1;
        Customer customer = customers[index];
        return customer;
    }

    public static void deleteCustomer(int id){
        //删除编号为id的客户对象， 下标 = 编号id - 1
        int index = id - 1;
        System.arraycopy(customers, index + 1, customers, index, count - index - 1);
            /*
            假设法： customers长度为10，count是5，index=1
                    存储的情况[0][1][2][3][4]
                    [2] -> [1] 就可以了
                    [3] -> [2] 就可以了
                    [4] -> [3] 就可以了
                    count-index-1
             */
        customers[--count] = null;
    }
}
